package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractTiktokByTimeApiHandler;
import com.ittx.dzt.tiktok.util.CyUtil;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增量下载订单
 * <p>
 * cy.salesOrder.download.byTimeFrame
 * /order/202309/orders/search （增量订单下载） https://partner.tiktokshop.com/docv2/page/650aa8094a0bb702c06df242?external_id=650aa8094a0bb702c06df242#Back%20To%20Top
 * </p>
 *
 * @author gywang
 * @since 2024-07-22
 */
@Slf4j
@Service
public class TiktokSalesOrderDownloadByTimeService extends AbstractTiktokByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 100;
	private static final String SHOP_ORDER_LIST = "orders";

	private static final String ORDER_ID = "id";

	@Autowired
	private TiktokSalesOrderDownloadByIdService tiktokSalesOrderDownloadByIdService;


	@Override
	protected String getMqTopic() {
		return TiktokApiConstant.Rocket.TIKTOK_DOWNLOAD_ORDER_SEARCHLIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getTiktokMethod() {
		return TiktokApiConstant.DOWNLOAD_ORDER_SEARCHLIST;
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
		if (validResult.hasError()) {
			return validResult;
		}
		String orderId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, orderId);
	}


	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {

		Map<String, Object> params = new HashMap<>();
		params.put("shop_cipher", getShopCipher(platformApiParamDTO));
		params.put("page_size", DEFAULT_PAGE_SIZE);
		Map<String, Object> reqBody = new HashMap<>();
		reqBody.put("update_time_ge", timeFrameDTO.getFrom().toEpochSecond(ZoneOffset.of("+8")));
		reqBody.put("update_time_lt", timeFrameDTO.getTo().toEpochSecond(ZoneOffset.of("+8")));

		// 状态过滤
		String status = CyUtil.getStatusStr(platformApiParamDTO, "sale");
		if (null != status) {
			reqBody.put("order_status", status);
		}

		Result<?> result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
		// 订单数量
		int total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
		String next_page_token = (String) dataMap.get("next_page_token");
		// 探查模式只返回总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get(SHOP_ORDER_LIST);
		if (CollectionUtil.isNotEmpty(list)) {
			// 分发数据到MQ，异步消费下载
			for (Map<String, Object> order : list) {
				String orderId = order.get(ORDER_ID).toString();
				sendToSplitTopic(platformApiParamDTO, orderId, logMap);
			}
		}
		while (StringUtils.isNotBlank(next_page_token)) {
			params.put("page_token", next_page_token);
			result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
			if (!result.isSuccess()) {
				return result;
			}
			resultMap = (Map<String, Object>) result.getData();
			dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
			list = (List<Map<String, Object>>) dataMap.get(SHOP_ORDER_LIST);
			if (CollectionUtil.isNotEmpty(list)) {
				// 分发数据到MQ，异步消费下载
				for (Map<String, Object> order : list) {
					String orderId = order.get(ORDER_ID).toString();
					sendToSplitTopic(platformApiParamDTO, orderId, logMap);
				}
			}
		}

		return Result.success(logMap);
	}

	/**
	 * sdk
	 * 根据单号查询单条订单信息-- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String orderId) {
		Result<?> result = tiktokSalesOrderDownloadByIdService.getOrderById(platformApiParamDTO, orderId);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param timeFrameDTO        接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		if (timeFrameDTO == null || platformApiParamDTO.getStoreConfig() == null ||
				timeFrameDTO.getTo() == null || timeFrameDTO.getFrom() == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), timeFrameDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}
}
